import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Park } from './park';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';

/*
  Generated class for the ParkDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ParkDataProvider {

  private readonly baseUrl: string = 'https://api2.bmob.cn/1';
  private readonly httpHeaders: HttpHeaders= new HttpHeaders({
      'X-Bmob-Application-Id' : '9b78974719f1e2b90e7121754c1028fa',
      'X-Bmob-REST-API-Key' : 'c76901292f32879e21bf5ca951ad00fb',
      'Content-Type' : 'application/json'
    });


  constructor(public http: HttpClient) {

  }


/**
 * 分页获取景区数据
 * @param num 获取个数
 * @param page 第几页
 */
  getParks(num: number, page: number): Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit', `${num}`)
    .set('skip', `${(page-1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
      {headers: this.httpHeaders, params: _params}).map(_ => _['results']);

  }
 
  /**
   * 获取记录数
   */
 getCount(): Observable<number>{
   return this.http.get<Number>(`${this.baseUrl}/classes/parks?limit=0&count=1`,
   {headers: this.httpHeaders}).map(data => data['count']);
 }
  
/**
 * 获取所有记录
 * @param total 记录总数 
 */
 getAllParks(total: number): Observable<Park[][]>{
   let all: Observable<Park[]>[] = [];
   for (let index = 0; index < total/500; index++) {
     let _params = new HttpParams()
     .set('limit','500')
     .set('skip', `${index*500}`);
    all[index] = this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,
    {headers: this.httpHeaders, params: _params}).map(_ => _['results']);
     
   }
   return Observable.forkJoin(all);
 }

}
